<template>
  <div class="list-content mainten-analysis-wrap">
    <el-row type="flex" justify="space-between">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
        <el-form-item v-if="$store.state.userinfo.isMuilUnitUser === 1">
          <el-select filterable @change="getTypeList()" v-model="searchForm.orgId" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgOptions"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <tree-select
            v-model="searchForm.categoryId"
            placeholder="请选择物联设备类别"
            filterable
            :width="200"
            :data="typeList"
            :defaultProps="typeDefaultProps"
            :nodeKey="typeNodeKey"
            :checkedKeys="checkedKeys"
            @node-click="handleNodeClick">
          </tree-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="getTableData(1)" v-model="searchForm.maintainType" placeholder="请选择维保类型">
            <el-option
                v-for="item in maintenanceTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="getTableData(1)" v-model="searchForm.workPeriod" placeholder="请选择维保周期">
            <el-option
                v-for="item in maintenanceCycleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getTableData(1)">查询</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-table
      v-if="loading"
      :data="tableData"
      :span-method="arraySpanMethod"
      ref="mainTable"
      style="width: 100%">
      <el-table-column fixed prop="fireSystemName" label="系统名称"  min-width="150"></el-table-column>
      <el-table-column fixed prop="assetCategoryName" label="资产类别" min-width="150"></el-table-column>
      <el-table-column fixed prop="workType" label="维保类型" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.workType == 1">维保巡查</div>
          <div v-else-if="scope.row.workType == 2">保养</div>
          <div v-else-if="scope.row.workType == 3">单点测试</div>
          <div v-else-if="scope.row.workType == 4">联动测试</div>
        </template>
      </el-table-column>
      <el-table-column fixed prop="workPeriod" label="作业周期" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.workPeriod == 1">月</div>
          <div v-if="scope.row.workPeriod == 2">季</div>
          <div v-if="scope.row.workPeriod == 3">半年</div>
          <div v-if="scope.row.workPeriod == 4">年</div>
        </template>
      </el-table-column>
      <el-table-column fixed prop="maintainStandardContent" label="作业内容" min-width="300">
        <template slot-scope="scope">
          <span v-for="item in scope.row.maintainStandardContent" :key="item.id">{{ item.workContent + ';' }}</span>
        </template>
      </el-table-column>
      <template>
        <el-table-column v-for="(obj, index) in timelineData" :label="obj.year + '年'" :key="index">
          <el-table-column v-for="(item, num) in obj.monthList" :key="num" :label="item + '月'" width="80">
            <template slot-scope="scope">
              <el-progress v-if="scope.row.itemList[getIndex(index, num)].percent !== false" :text-inside="true" :stroke-width="26" :percentage="scope.row.itemList[getIndex(index, num)].percent*100"></el-progress>
              <p v-else></p>
            </template>
          </el-table-column>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      background
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :current-page.sync="currentPage"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import { getAssetsCategoryId, getAssetsCategoryIdWithAssets } from '@/api/assets'
import { getOrgList } from '@/api/org'
import util from '@/utils/util'
import { getMaintainListForAnalysis } from '@/api/analysisReport'

const MapColumn = {
  '1': 1, // 月
  '2': 3, // 季度
  '3': 6, // 半年
  '4': 12 // 年
}
export default {
  name: 'FireSystemDimension',
  components: {
    TreeSelect
  },
  data () {
    return {
      loading: false,
      orgOptions: [],
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'categoryList',
        label: 'name',
        value: 'id'
      },
      typeNodeKey: 'id',
      checkedKeys: [],
      // 维保类型
      maintenanceTypeOptions: [
        {
          id: 0,
          name: '全部维保类型' 
        },{
          id: 1,
          name: '维保巡查' 
        }, {
          id: 2,
          name: '保养' 
        }, {
          id: 3,
          name: '单点测试'  
        }, {
          id: 4,
          name: '联动测试' 
        }
      ],
      // 维保周期
      maintenanceCycleOptions: [
        {
          id: 0,
          name: '全部维保周期'
        }, {
          id: 1,
          name: '月'
        }, {
          id: 2,
          name: '季'
        }, {
          id: 3,
          name: '半年'
        }, {
          id: 4,
          name: '年'
        },
      ],
      // 搜索条件
      searchForm: {
        orgId: this.$store.state.userinfo.isMuilUnitUser === 1 ? Number(this.$store.state.userinfo.organizationIds.split(',')[0]) : this.$store.state.userinfo.org.id, // 业主单位
        fireSystemId: '', // 消防系统id
        categoryId: '', // 消防系统树结构
        maintainType: 0, // 维保类型
        workPeriod: 0 // 维护周期
      },
      // 表格数据
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 维保时间
      maintainStartTime: '',
      mantainEndTime: '',
      timelineData: [],
    }
  },
  created:function() {
    let that = this

    if(that.$store.state.userinfo.isMuilUnitUser === 1) {
      // 获取业主单位信息
      getOrgList({
        queryType: 0
      }).then(res => {
        if(res.status = 200) {
          that.orgOptions = res.data
          that.searchForm.orgId = that.orgOptions[0].organizationId

          that.getTypeList()
        }
      })
    } else {
      this.getTypeList()
    }
  },
  methods: {
    getTypeList() {
      let that = this
      that.searchForm.categoryId = ''
      that.checkedKeys = []
      getAssetsCategoryIdWithAssets({
        orgId: that.searchForm.orgId
      }).then(res => {
        // 加上全部
        res.data.unshift({
          id: '',
          name: '全部物联设备类别'
        })
        that.typeList = res.data
        // 默认选择全部
        that.$nextTick(() => {
          that.checkedKeys = ['']
        })
        that.getTableData(1)
      })
    },
    // 消防系统与设备类别树被点击
    handleNodeClick(obj, node, item) {
      let that = this
      if(obj.hasOwnProperty('fireSystemKey')) {
        // 记录系统id，不记录设备类别id
        that.searchForm.fireSystemId = obj.fireSystemKey
        that.searchForm.categoryId = ''
      } else {
        // 不记录系统id，记录设备类别id
        that.searchForm.fireSystemId = ''
        that.searchForm.categoryId = obj.id
      }
      that.getTableData(1)
    },
    // 获取列表数据
    getTableData(pageIndex, pageSize) {
      let that = this
      that.loading = false
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        orgId: that.searchForm.orgId,
        fireSystemId: that.searchForm.fireSystemId || 0,
        categoryId: that.searchForm.fireSystemId ? 0 : (that.searchForm.categoryId || 0),
        maintainType: that.searchForm.maintainType,
        workPeriod: that.searchForm.workPeriod,
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1
      }
      getMaintainListForAnalysis(parames).then(res => {
        // var res = {"status":200,"info":"操作成功","total":14,"data":{"mantainEndTime":"2020-05-28 00:00:00","maintainStartTime":"2019-05-28 00:00:00","total":14,"rows":[{"fireSystemName":"消火栓系统","workContent":"","updateTime":"2019-05-11 16:15:53","workPeriod":4,"createAccount":"","updateAccount":"","workStandard":"对易污染、易腐蚀生锈的消防设备应定期清洁、除锈、注润滑油","fireSystem":11,"createTime":"2019-05-11 16:15:53","assetCategoryId":178,"workType":2,"itemList":[{"startTime":"2019-05-29 00:00:00","endTime":"2020-04-30 23:59:59","maintainTaskId":117,"percent":"0"}],"id":38,"maintainStandardContent":[{"result":"","createTime":"2019-05-11 16:15:53","workContent":"清洁","standardId":14,"updateTime":"2019-05-11 16:15:53","createAccount":"","id":47,"type":1,"standardDetailId":38,"updateAccount":""},{"result":"","createTime":"2019-05-11 16:15:53","workContent":"除锈","standardId":14,"updateTime":"2019-05-11 16:15:53","createAccount":"","id":48,"type":1,"standardDetailId":38,"updateAccount":""}],"assetCategoryName":"室内消火栓","maintainStandardId":14}]}}
        let arr = res.data.rows
        
        that.maintainStartTime = res.data.maintainStartTime
        that.mantainEndTime = res.data.mantainEndTime
        // if(res.data.maintainStartTime && res.data.mantainEndTime) {
          that.timelineData = that.calculateTimeLine(that.maintainStartTime, that.mantainEndTime) //(res.data.maintainStartTime, res.data.mantainEndTime)
          // 计算进度条展示数据
          for(let i=0, len=arr.length; i < len; i++) {
            arr[i].itemList = that.reSetItemList(res.data.rows[i])
          }
          that.tableData = arr
        // }
        that.total = res.total
        that.loading = true
      })
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.getTableData(currentPage)
    },
    // 计算时间表头
    calculateTimeLine(maintainStartTime, mantainEndTime) {
      let that = this
      let arr = []
      let startTime = new Date(maintainStartTime)
      let endTime = new Date(mantainEndTime)
      // 开始时间对象
      let startObj = {
        year: Number(startTime.getFullYear()),
        month: Number(startTime.getMonth()) + 1,
      }
      // 结束时间对象
      let endObj = {
        year: Number(endTime.getFullYear()),
        month: Number(endTime.getMonth()) + 1,
      }
      let yearSpan = endObj.year - startObj.year + 1 // 年跨度

      for(var i=0; i < yearSpan; i++) {
        let obj = {
          year: startObj.year + i,
          monthList: []
        }
        if(obj.year == startObj.year) {
          if(obj.year == endObj.year) { // 开始、结束时间在同一年内
            for(var k=0, len=(endObj.month-startObj.month+1); k < len; k++) {
              obj.monthList.push(startObj.month + k)
            }
          } else { // 开始、结束时间不在同一年
            for(var k=0, len=(12-startObj.month)+1; k < len; k++) {
              obj.monthList.push(startObj.month + k)
            }
          }
        } else if (obj.year == endObj.year) {
          for(var k=0, len=endObj.month; k < len; k++) {
            obj.monthList.push(1 + k)
          }
        } else if (obj.year > startObj.year && obj.year < endObj.year) {
          obj.monthList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ]
        }
        obj.year = obj.year
        arr.push(obj)
      }
      return arr
    },
    /* 
     * 判断是否为当前年月
     * currentYear-当前年 currentMonth-当前月 time-时间点
     */
    isCurrentTime(currentYear, currentMonth, time) {
      let that = this
      let timeObj = new Date(time)

      if (currentYear == timeObj.getFullYear() && currentMonth == (timeObj.getMonth()+1)) {
        return true
      } else {
        return false
      }
    },
    /* 
     * 判断是否在周期内
     * currentYear-当前年 currentMonth-当前月 time-时间点
     */
    includeTime(startTime, endTime, currentTime) {
      let that = this
      let startDate = new Date(startTime).getTime()
      let endDate = new Date(endTime).getTime()
      let currentDate = new Date(currentTime).getTime()

      if(startDate < currentDate && endDate > currentDate) {
        return true
      } else {
        return false
      }
    },
    // itemList重组
    reSetItemList(row) {
      let that = this
      let timelineData = that.timelineData
      let itemList = row.itemList
      let newArr = []

      for(let i=0; i < timelineData.length; i++) {
        for(let j=0; j < timelineData[i].monthList.length; j++) {
          let currentYear = timelineData[i].year
          let currentMonth = timelineData[i].monthList[j]
          let currentDate = currentYear + '-' + currentMonth + '-01 00:00:00'
          let hasData = false
          
          for (let k=0; k < itemList.length; k++) {
            if(that.isCurrentTime(currentYear, currentMonth, itemList[k].startTime)) { // 当前年月有数据
              hasData = true
              // 根据周期设置跨几列
              itemList[k].column = MapColumn[row.workPeriod]
              newArr.push(itemList[k])
              break
            } else if (that.includeTime(itemList[k].startTime, itemList[k].endTime, currentDate)) { // 当前年月在有数据的周期内
              hasData = true
              newArr.push({
                percent: false,
                column: 0
              })
              break
            }
          }
          if(!hasData) {
            newArr.push({
              percent: false,
              column: 1
            }) 
          }
        }
      }

      return newArr
    },
    // 合并行或列
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if(columnIndex > 4) {
        // 合并列
        return [1, row.itemList[columnIndex-5].column]
      }
    },
    // 获取当前列的序号
    getIndex(index, num) {
      let that = this
      let sum = 0
      if(index > 0) {
        while(index > 0) {
          index -= 1
          sum += that.timelineData[index].monthList.length
        }
        return sum + num
      } else {
        return num
      }
    }
  },
}
</script>
<style lang="scss">
.mainten-analysis-wrap {
  td {
    .el-progress-bar__outer {
      background-color: #c0c0c0;
    }
  }
}
</style>

